package game.module.ddz.processor;

import java.util.List;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.ddz.bean.DdzRound;
import game.module.ddz.logic.DdzDataManager;
import game.module.ddz.logic.DdzLogic;
import game.session.SessionManager;
import lion.common.ArrayUtility;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageDdz.C2SDdzJiaoDiZhu;
import lua.LuaMessageDdz.PushDdzFaPai2;
import lua.LuaMessageDdz.PushDiZhuSelect;
import lua.LuaMessageDdz.PushJiaoDiZhu;
import lua.LuaMessageDdz.S2CDdzJiaoDiZhu;
import lua.LuaMessageLogin.S2ErrorCode;

@MsgCodeAnn(msgcode = C2SDdzJiaoDiZhu.id, accessLimit = 500)
public class DdzJiaoDiZhuProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(DdzJiaoDiZhuProcessor.class);

	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw request) throws Exception {
		C2SDdzJiaoDiZhu reqMsg = C2SDdzJiaoDiZhu.parse(request);
		short call_id = reqMsg.is_call;
		int playerId = playingRole.getId();
		logger.info("ddz jiao dizhu,playerId={},call_id={}", playerId, call_id);
		// 房间是否存在
		DdzRound ddzRound = DdzDataManager.getInstance().getDdzRoom(playerId);
		if (ddzRound == null) {
			S2ErrorCode respMsg = new S2ErrorCode(201);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		//房间类型是否正确
		if(ddzRound.getJiaoFenOrQiang() == 2) {
			S2ErrorCode respMsg = new S2ErrorCode(208);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// 还有玩家没有准备好
		if (ddzRound.getConnectedPlayerIndexSet() == null
				|| ddzRound.getConnectedPlayerIndexSet().size() < ddzRound.getPlayerIds().size()) {
			S2ErrorCode respMsg = new S2ErrorCode(215);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// 是否我的回合
		int currentJiaoDiZhuIndex = ddzRound.getJiaoDiZhuIndex();
		int myIndex = ddzRound.getPlayerIds().indexOf(playerId);
		if (myIndex != currentJiaoDiZhuIndex) {
			S2ErrorCode respMsg = new S2ErrorCode(202);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// 是否已经产生地主
		if (ddzRound.getDiZhuIndex() != null) {
			S2ErrorCode respMsg = new S2ErrorCode(203);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// 分数是否比之前的大
		if (ddzRound.getLastJiaoScore() != null && call_id > 0) {
			short lastScore = ddzRound.getLastJiaoScore();
			if (call_id <= lastScore) {
				S2ErrorCode respMsg = new S2ErrorCode(204);
				playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
				return;
			}
		}
		// 推送
		int nextJiaoDiZhuIndex = currentJiaoDiZhuIndex + 1;
		if (nextJiaoDiZhuIndex >= 3) {
			nextJiaoDiZhuIndex = 0;
		}
		PushJiaoDiZhu pushJiaoDiZhu = new PushJiaoDiZhu((short) myIndex, (short) nextJiaoDiZhuIndex, call_id);
		List<Integer> playerIds = ddzRound.getPlayerIds();
		for (Integer aPlayerId : playerIds) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushJiaoDiZhu.build(pr.alloc()));
			}
		}
		// 我叫的分数
		if (call_id >= 3) {
			ddzRound.setLastJiaoScore(call_id);
			ddzRound.setLastJiaoIndex((short) myIndex);
			// 我是地主
			selectDiZhu(ddzRound, myIndex,call_id);
		} else {
			int newLoopCount = ddzRound.getLoopCount() + 1;
			logger.info("叫地主次数={}", newLoopCount);
			if (newLoopCount >= 3) {
				if (call_id > 0) {
					ddzRound.setLastJiaoScore(call_id);
					ddzRound.setLastJiaoIndex((short) myIndex);
					// 我是地主
					selectDiZhu(ddzRound, myIndex,call_id);
				} else {
					// 没人叫，随机一个地主
					if (ddzRound.getLastJiaoIndex() != null) {
						selectDiZhu(ddzRound, ddzRound.getLastJiaoIndex(),ddzRound.getLastJiaoScore());
					} else {
						reFaPai(ddzRound);
					}
				}
			} else {
				currentJiaoDiZhuIndex++;
				if (currentJiaoDiZhuIndex >= 3) {
					currentJiaoDiZhuIndex = 0;
				}
				ddzRound.setJiaoDiZhuIndex(currentJiaoDiZhuIndex);
				ddzRound.setLoopCount(newLoopCount);
				if (call_id > 0) {
					ddzRound.setLastJiaoScore(call_id);
					ddzRound.setLastJiaoIndex((short) myIndex);
				}
			}
		}
		S2CDdzJiaoDiZhu respMsg = new S2CDdzJiaoDiZhu();
		playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
	}

	/**
	 * 没人叫地主，重新发牌
	 * @param ddzRound
	 */
	private void reFaPai(DdzRound ddzRound) {
		DdzLogic.getInstance().randCard(ddzRound);
		int jiaoDiZhuIndex = RandomUtils.nextInt(0, 3);
		ddzRound.setJiaoDiZhuIndex(jiaoDiZhuIndex);
		ddzRound.setLoopCount(0);
		PushDdzFaPai2 pushFaPai2 = new PushDdzFaPai2();
		pushFaPai2.di_cards = ArrayUtility.toByteArray(ddzRound.getDi());
		pushFaPai2.jiao_dizhu_index = (short)jiaoDiZhuIndex;
		List<Integer> playerIdList = ddzRound.getPlayerIds();
		int playerIndex = 0;
		for (Integer aPlayerId : playerIdList) {
			List<Byte> cardList = ddzRound.getCards().get(playerIndex++);
			pushFaPai2.my_cards = ArrayUtility.toByteArray(cardList);
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushFaPai2.build(pr.alloc()));
			}
		}
	}

	private void selectDiZhu(DdzRound ddzRound, int myIndex, short jiaoScore) {
		ddzRound.setDiZhuIndex(myIndex);
		ddzRound.setChuPaiIndex(myIndex);
		ddzRound.setRoundScore(jiaoScore);
		// 推送消息
		PushDiZhuSelect pushDiZhuSelect = new PushDiZhuSelect((short) myIndex);
		List<Integer> playerIds = ddzRound.getPlayerIds();
		for (Integer aPlayerId : playerIds) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushDiZhuSelect.build(pr.alloc()));
			}
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

}
